<!DOCTYPE html>
<html th:replace="~{fragments/main :: layout(~{::title}, ~{::section}, ~{::popwin})}"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <title>客服管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
</head>
<body>
<section>
    <div class="layui-form">
        <div class="layui-form-item">
            <label class="layui-form-label">公司名称：</label>
            <div class="layui-input-block">
                <label class="layui-form-label" style="text-align: left">[[${user.companyName}]]</label>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">用户名：</label>
            <div class="layui-input-block">
                <label class="layui-form-label" style="text-align: left">[[${user.userName}]]</label>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">状态：</label>
            <div class="layui-input-block">
                <label class="layui-form-label" style="text-align: left">[[${user.id} == 0? '启用':'禁用' ]]</label>
            </div>
        </div>
        <div class="layui-form-item" th:if="${user.id} != null">
            <label class="layui-form-label">有效期：</label>
            <div class="layui-input-block">
                <label class="layui-form-label" style="text-align: left; width: 100%">[[${#dates.format(user.expireDate,
                    'yyyy-MM-dd HH:mm:ss')}]]</label>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button id="btnAdd" class="layui-btn" lay-filter="formDemo">增加微信号</button>
                <button class="layui-btn layui-btn-primary">重置密码</button>
                <a href="/admin/manage" class="layui-btn layui-btn-primary">返回</a>
            </div>
        </div>
    </div>
    <table id="wx-table" lay-filter="test"></table>
    <script src="/layui/layui.js"></script>
    <style type="text/css">
        .layui-table-cell {
            height: auto;
            line-height: 28px;
        }
    </style>
    <script th:inline="javascript">
        layui.use(['form', 'laydate', 'table', 'layer'], function () {
            var form = layui.form;
            var $ = layui.jquery;
            var laydate = layui.laydate;
            form.render({});
            form.on('submit(formAddAccount)', function (data) {
                $.ajax({
                    url: '/device/createCodes',
                    type: 'post',
                    data: JSON.stringify(data.field),
                    contentType: "application/json;charset=utf-8",
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 500) {
                            layer.msg(data.msg, {icon: 5});//失败的表情
                            return;
                        } else {
                            layer.msg(data.msg, {
                                icon: 6,//成功的表情
                                time: 1000 //1秒关闭（如果不配置，默认是3秒）
                            }, function () {
                            });
                        }
                    },
                    complete: function () {
                        layer.close(this.layerIndex);
                        window.location = window.location;
                    }
                });
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });

            form.on('submit(formExpire)', function (data) {
                var itmeData = window.data;
                itmeData.expireDate = $("#txtExpire").val();
                $.ajax({
                    url: '/device/update',
                    type: 'post',
                    data: JSON.stringify(itmeData),
                    contentType: "application/json;charset=utf-8",
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 500) {
                            layer.msg(data.msg, {icon: 5});//失败的表情
                            return;
                        } else {
                            layer.msg(data.msg, {
                                icon: 6,//成功的表情
                                time: 1000 //1秒关闭（如果不配置，默认是3秒）
                            }, function () {
                            });
                        }
                    },
                    complete: function () {
                        layer.close(this.layerIndex);
                        window.location = window.location;
                    }
                });
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });

            $("#btnAdd").click(function () {
                parent.layer.open({
                    type: 1,
                    area: ["500px", '500px'],
                    content: $('#addAccountWin') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                });
            });

            var resetStatus = function (obj) {
                var data = obj.data;
                var title = "";
                if (data.status == 1) {
                    data.status = 0;
                    title = "确定启用该KEY吗？";
                } else {
                    data.status = 1;
                    title = "确定禁用该KEY吗？";
                }
                layer.confirm(title, {
                    icon: 3,
                    skin: 'layer-ext-moon',
                    btn: ['确认', '返回']
                }, function () {
                    $.ajax({
                        url: '/device/update',
                        type: 'post',
                        data: JSON.stringify(data),
                        contentType: "application/json;charset=utf-8",
                        dataType: 'json',
                        beforeSend: function () {
                            this.layerIndex = layer.load(0, {shade: [0.5, '#393D49']});
                        },
                        success: function (data) {
                            if (data.code == 500) {
                                layer.msg(data.msg, {icon: 5});//失败的表情
                                return;
                            } else {
                                layer.msg(data.msg, {
                                    icon: 6,//成功的表情
                                    time: 1000 //1秒关闭（如果不配置，默认是3秒）
                                }, function () {
                                    tableIns.reload({})
                                });
                            }
                        },
                        complete: function () {
                            layer.close(this.layerIndex);
                        },
                    });
                });
            };

            //执行一个laydate实例
            laydate.render({
                elem: '#txtNewExpire' //指定元素
            });
            //执行一个laydate实例
            laydate.render({
                elem: '#txtExpire' //指定元素
            });

            var userId = /*[[${user.id}]]*/ 0;

            if (userId > 0) {
                var table = layui.table;

                var cols = [ //表头
                    {field: 'keyId', title: '编号', width: 80},
                    {field: 'deviceKey', title: '接入码', width: 200},
                    {field: 'expireDate', title: '有效期'},
                    {title: '设备连接', templet: '#statusTpl'},
                    {title: '绑定微信', templet: '#wechatTpl'},
                    {title: '状态', templet: '#statTpl'},
                    {title: '操作', templet: '#opTpl'}
                ];
                var udpateExpire = function (obj) {
                    window.data = obj.data;
                    $("#txtExpire").val(obj.data.expireDate);
                    parent.layer.open({
                        type: 1,
                        area: ["400px", '400px'],
                        content: $('#expireWin') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    });
                }
                //执行渲染
                var tableIns = table.render({
                    elem: '#wx-table', //指定原始表格元素选择器（推荐id选择器）
                    response: {
                        statusName: 'code' //规定数据状态的字段名称，默认：code
                        , statusCode: 200 //规定成功的状态码，默认：0
                        , msgName: 'message' //规定状态信息的字段名称，默认：msg
                        , dataName: 'data' //规定数据列表的字段名称，默认：data
                    }
                    , url: "/device/list?userId=[[${user.id}]]"
                    , cols: [
                        cols
                    ],
                    id: 'wxTable'
                });
                table.resize('wxTable');
                table.on('tool(test)', function (obj) {
                    var data = obj.data; //获得当前行数据
                    var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                    var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
                    if (layEvent == 'enableUser') {
                        resetStatus(obj);
                    } else if (layEvent == 'disableUser') {
                        resetStatus(obj);
                    } else if (layEvent == 'udpateExpire') {
                        udpateExpire(obj);
                    }
                })
            }
        });
    </script>
    <script type="text/html" id="Tpl">
        <div class="layui-btn-container">
            {{# if(d.avatar != undefined && d.avatar != null && d.avatar != ""){ }}
            <img src="{{d.avatar}}" style="height: 64px; width: 64px;">
            {{# } else { }}
            <img src="https://www.agri35.com/UploadFiles/img_0_1093847288_3038136586_26.jpg"
                 style="height: 64px; width: 64px;">
            {{# } }}

        </div>
    </script>
    <script type="text/html" id="opTpl">
        {{#  if(d.status == 1){ }}
        <a class="layui-btn layui-btn-sm" lay-event="disableUser">启用</a>
        {{#  } else { }}
        <a class="layui-btn layui-btn-sm" lay-event="enableUser">禁用</a>
        {{#  } }}
        <a class="layui-btn layui-btn-sm" lay-event="udpateExpire">修改有效期</a>
    </script>
    <script type="text/html" id="wechatTpl">
        {{#  if(d.alias != undefined && d.alias != null && d.alias != ""){ }}
                {{=d.alias}}
        {{#  } else { }}
                {{=d.wxId}}
        {{#  } }}
    </script>
    <script type="text/html" id="statusTpl">
        {{#  if(d.realUdid != undefined && d.realUdid != null && d.realUdid != ""){ }}
        已接入
        {{#  } else { }}
        未接入
        {{#  } }}
    </script>
    <script type="text/html" id="statTpl">
        {{#  if(d.status == 1 ){ }}
        禁用
        {{#  } else { }}
        启用
        {{#  } }}
    </script>
</section>
<th:block th:fragment="popwin">
    <div id="addAccountWin" style="display: none">
        <div class="layui-form" style="margin-top: 10px">
            <div class="layui-form-item">
                <input type="hidden" name="id" lay-filter="user" th:value="${user.id}"/>
                <label class="layui-form-label" style="width: 100px;">微信号数量：</label>
                <div class="layui-input-inline">
                    <input type="text" name="wxCount" required lay-verify="required|number" placeholder="微信号数量"
                           autocomplete="off" class="layui-input" lay-filter="user"/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;">有效期：</label>
                <div class="layui-input-inline">
                    <input type="text" name="expireDate" id="txtNewExpire" required lay-verify="required" placeholder="账号名称"
                           autocomplete="off" class="layui-input" lay-filter="user"/>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formAddAccount">保存</button>
                    <button class="layui-btn layui-btn-primary" onclick="layer.close(layer.index);">关闭</button>
                </div>
            </div>
        </div>
    </div>
    <div id="expireWin" style="display: none">
        <div class="layui-form" style="margin-top: 10px">
            <div class="layui-form-item">
                <label class="layui-form-label" style="width: 100px;">有效期：</label>
                <div class="layui-input-inline">
                    <input type="text" name="expireDate" id="txtExpire" required lay-verify="required" placeholder="有效期"
                           autocomplete="off" class="layui-input" lay-filter="user"/>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="formExpire">保存</button>
                    <button class="layui-btn layui-btn-primary" onclick="layer.close(layer.index);">关闭</button>
                </div>
            </div>
        </div>
    </div>
</th:block>
</body>
</html>